package com.nut.lmsc.util;

import com.alibaba.excel.EasyExcel;
import org.apache.commons.collections4.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

public class ExcelUtil {

    /**
     * excel导出
     * @param response
     * @param sheetName
     * @param dataList
     */
    public static void simpleDownload(HttpServletResponse response, String sheetName, List<?> dataList) {
        simpleDownload(response, sheetName, dataList, null);
    }

    public static void simpleDownload(HttpServletResponse response, String sheetName, List<?> dataList, List<List<String>> headers) {
        if (sheetName == null) sheetName = "示例";
        if (CollectionUtils.isEmpty(dataList)) return;
        Class<?> Clazz = dataList.get(0).getClass();
        String timeStr = DateUtil.getNowDate();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode(sheetName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + timeStr + ".xlsx");
            EasyExcel.write(response.getOutputStream(), Clazz).sheet(sheetName).head(headers).doWrite(dataList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
